package net.xdclass.component;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.SmsConfig;
import net.xdclass.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @Description 短信组件
 * @Author lihw
 * @Date 2023/4/14 22:46
 */
@Component
@Slf4j
public class SmsComponent {

    /**
     * 发送地址
     */
    private static final String SMS_SEND_API = "http://dfsns.market.alicloudapi.com/data/send_sms";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;

    /**
     * 发送短信验证码
     *
     * @param to
     * @param templateId CST_hecci10120
     * @param value
     */
    public void send(String to, String templateId, String value)  {
        long beginTime = CommonUtil.getCurrentTimestamp();

        HttpHeaders headers = new HttpHeaders();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.add("Authorization", "APPCODE " + smsConfig.getAppCode());
        // 设置请求类型为 x-www-form-urlencoded
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // form表单的参数
        MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("content", "code: " + value);
        postParameters.add("phone_number", to);
        postParameters.add("template_id", templateId);

        HttpEntity entity = new HttpEntity<>(postParameters, headers);

        ResponseEntity<String> response = restTemplate.exchange(SMS_SEND_API, HttpMethod.POST, entity, String.class);
        long endTime = CommonUtil.getCurrentTimestamp();

        log.info("耗时={},url={},body={}", endTime - beginTime, SMS_SEND_API, response.getBody());
        if (response.getStatusCode().is2xxSuccessful()) {
            log.info("发送短信验证码成功");
        } else {
            log.error("发送短信验证码失败:{}", response.getBody());
        }

    }


}
